<template>
<div class="adoptAttrs">
  <div class="tree-page">
    <el-alert
      style="flex-shrink: 0"
      title="规格的添加与删除会导致已录入的sku失效，请务必谨慎操作！！"
      type="error"></el-alert>
    <search-block>
      <template slot="button">
        <el-button @click="doFilter">查询</el-button>
        <el-button type="primary" @click="addSpec()" v-if="!isView && lockStatus !== '1'">添加规格</el-button>
      </template>
      <el-form inline :model="search" label-width="100px" @submit.native.prevent>
        <el-form-item label="规格名称:">
          <el-input v-model="search.name" clearable></el-input>
        </el-form-item>
      </el-form>
    </search-block>
    <div class="spec-tree-block tree-block tree-page-block">
      <el-tree
        :key="treeKey"
        ref="tree"
        :data="specData"
        accordion
        node-key="specCode"
        :filter-node-method="filterNode"
        :props="{ label: 'specName', children: 'children' }"
        lazy
        :load="loadChild">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span class="tree-node-label">{{ node.label }}</span>
        <span class="tree-node-btn" v-if="!isView">
          <el-link
            v-if="lockStatus !== '1'"
            :underline="false"
            type="primary"
            @click="() => addSpec(node)">
            添加规格项
          </el-link>
          <el-link
              :underline="false"
              type="primary"
              @click="() => editSpec(node)">
            编辑
          </el-link>
          <el-popconfirm
            v-if="lockStatus !== '1'"
            title="是否确认删除该规格项？"
            @confirm="delSpec(data)">
            <el-link
                disabled
                slot="reference"
                :underline="false"
                type="danger">
              删除
            </el-link>
          </el-popconfirm>
        </span>
      </span>
      </el-tree>
    </div>
    <y-form
      :key="refreshKey"
      v-model="forms.formModel"
      append-to-body
      :visible.sync="forms.showForm"
      :title="forms.formTypeTitle[forms.formsType]"
      width="50%"
      destroy-on-close
      :formAttrs="forms.formAttrs"
      :columns="getFormColumns()"
      @close="refreshKey+=2"
      @ensure="ensureModel">
      <template slot="specLevel">
        <el-input v-model="forms.formModel.specLevel" disabled style="width: 50px;margin-right: 10px"></el-input>级
      </template>
    </y-form>
  </div>
</div>
</template>

<script>
export default {
  name: "adoptAttrs",
  props:{
    adoptId: String,
    lockStatus: String,
    isView:{
      type: Boolean,
      default: false
    }
  },
  data(){
    return{
      search:{
        name: ''
      },
      specData: [],
      refreshKey: 0,
      treeKey: 1,
      filterTag: false,
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加规格',
          'EDIT': '编辑规格'
        },
        currentForm: null,
        formModel: {
          id: '',
          specCode: '',
          specName: '',
          specPcode: null,
          specPname: '',
          specLevel: 1,
          orderNum: ''
        },
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            specCode: [
              {required: true, message: "请输入规格编码", trigger: "blur"},
              {
                validator: (rule, value, callback) => {
                  if(this.forms.formsType === 'EDIT'){
                    callback();
                  }else {
                    this.$$validateCode(
                        this.$api.adopt.validateSpecCode,
                        {
                          specCode: value,
                          adoptId: this.adoptId
                        }, callback);
                  }
                },
                trigger: 'blur'
              }
            ],
            specName: [{required: true, message: "请选择规格名称", trigger: "blur"}]
          }
        }
      }
    }
  },
  methods:{
    refresh(){
      this.treeKey+=2;
      this.filterTag = true;
    },
    showYForm(){
      this.forms.showForm = true;
    },
    getFormColumns(){
      return [
        {
          label: "上一级规格",
          prop: "specPname",
          comp:{
            compType: 'input',
            attrs:{
              disabled: true
            }
          }
        },
        {
          label: "规格编码",
          prop: "specCode",
          comp:{
            compType: 'input',
            attrs:{
              clearable: true,
              disabled: this.forms.formsType === 'EDIT',
              maxlength: 10,
              showWordLimit: true
            }
          }
        },
        {
          label: "规格名称",
          prop: "specName",
          comp:{
            compType: 'input',
            attrs:{
              clearable: true,
              maxlength: 30,
              showWordLimit: true
            }
          }
        },
        {
          label: "当前级别",
          prop: "specLevel",
          template: true
        },
        {
          label: "排序",
          prop: "orderNum",
          comp:{
            compType: 'input-number',
          }
        }
      ]
    },
    doFilter(){
      this.$refs.tree.filter(this.search.name);
    },
    filterNode(value, data){
      if (!value) return true;
      return data.specName.indexOf(value) >= 0
    },
    loadChild(node,resolve){
      this.$yAxios({
        url: this.$api.adopt.getAdoptSpecChild,
        data:{
          adoptId: this.adoptId,
          specPcode: node.data.specCode || null
        }
      },info => {
        if(this.filterTag){
          this.filterTag = false;
          this.$nextTick(() => {
            this.doFilter();
          })
        }
        resolve(info)
      }, () => {
        resolve([])
      })
    },
    validDelete(data){
      return new Promise(resolve => {
        this.$yAxios({
          url: this.$api.adopt.getAdoptSpecChild,
          data:{
            specPcode: data.specCode
          },
          loading: true
        },info => {
          resolve(Array.isArray(info) && !info.length)
        }, () => {
          resolve(false)
        })
      })
    },
    resetForm(data = this.forms.currentForm){
      this.forms.formModel = Object.assign({
        id: '',
        specCode: '',
        specName: '',
        specPcode: null,
        specPname: '',
        specLevel: 1,
        orderNum: ''
      }, data)
    },
    addSpec({level, data} = {level: 0, data: {id: '', specName: '无'}}){
      console.log(data);
      if(level === 0){
        let _root = this.$refs['tree'].root, _roots = _root.childNodes;
        if(Array.isArray(_roots) && _roots.length > 0){
          this.$message({
            type: 'warning',
            message: '已存在其他规格，不可添加新规格'
          });
          return;
        }
      }else{
        let _node = this.$refs['tree'].getNode(data), _children = _node.childNodes;
        if(Array.isArray(_children) && _children.length > 0){
          this.$message({
            type: 'warning',
            message: '已存在其他规格，不可添加新规格'
          });
          return;
        }
      }
      if(level === 2){
        this.$alert('无法在2级目录下添加规格', {
          confirmButtonText: '确定'
        });
        return;
      }
      this.forms.formsType = 'ADD';
      this.forms.currentForm = data;
      this.resetForm({
        specPcode: data.specCode || null,
        specPname: data.specName,
        specLevel: +level + 1
      });
      this.showYForm();
    },
    editSpec({level, data}){
      this.forms.formsType = 'EDIT';
      let pNode = this.$refs['tree'].getNode(data.specPcode || '');
      if(pNode){
        data.specPname = pNode.data.specName;
      }
      this.forms.currentForm = data;
      this.resetForm();
      this.showYForm();
    },
    async delSpec(data){
      let deleteAble = await this.validDelete(data)
      if(!deleteAble){
        await this.$alert('无法删除包含子品种的物品种类', {
          confirmButtonText: '确定'
        });
        return;
      }
      this.$yAxios({
        url: this.$api.adopt.removeAdoptSpec,
        data:{
          ids: [data.id]
        },
        loading: true
      }, info => {
        let pArray = this.specData, pId = data.parentId
        if(pId){
          let PNode = this.$refs['tree'].getNode(pId);
          pArray = PNode.data.children;
        }
        //let index = pArray.indexOf(data);
        this.$refs['tree'].remove(data);
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        //this.$emit("reset-sku");
      })
    },
    ensureModel(form){
      let newForm, url;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
        url = this.$api.adopt.saveAdoptSpec;
      }else{
        newForm = Object.assign({ adoptId: this.adoptId }, form);
        url = this.$api.adopt.saveAdoptSpec
      }
      this.$yAxios({
        url,
        data: newForm,
        loading: true
      }, info => {
        if(info) newForm = info;
        switch(this.forms.formsType){
          case 'ADD':{
            if(this.forms.currentForm && this.forms.currentForm.id){//添加规格项
              if(!this.forms.currentForm.children){
                this.$set(this.forms.currentForm, 'children', []);
              }
              this.$refs['tree'].getNode(this.forms.currentForm).expanded = true;
              this.$refs['tree'].append(newForm, this.forms.currentForm);
            }else{//添加规格
              this.refresh();
            }
            break;
          }
          case 'EDIT':{
            Object.assign(this.forms.currentForm, newForm);
            break;
          }
        }
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        //this.$emit("reset-sku");
      })
    },
    save(){
      return new Promise(resolve => {
        resolve();
      });
    }
  }
}
</script>

<style scoped>

</style>